"""
排序算法API接口
"""
from typing import List, Dict, Any
from common.logger import get_logger
from .bubble_sort import bubble_sort, optimized_bubble_sort
from .insertion_sort import insertion_sort, optimized_insertion_sort
from .quick_sort import quick_sort
from .select_sort import selection_sort
from .shell_sort import shell_sort

logger = get_logger(__name__)


class SortAPI:
    """排序算法API类"""
    
    def __init__(self):
        self.algorithms = {
            "bubble_sort": bubble_sort,
            "optimized_bubble_sort": optimized_bubble_sort,
            "insertion_sort": insertion_sort,
            "optimized_insertion_sort": optimized_insertion_sort,
            "quick_sort": quick_sort,
            "selection_sort": selection_sort,
            "shell_sort": shell_sort
        }
    
    def get_available_algorithms(self) -> List[str]:
        """获取可用的排序算法列表"""
        return list(self.algorithms.keys())
    
    def sort_data(self, algorithm: str, data: List[Any], **kwargs) -> Dict[str, Any]:
        """使用指定算法对数据进行排序"""
        if algorithm not in self.algorithms:
            raise ValueError(f"不支持的排序算法: {algorithm}")
        
        logger.info(f"使用算法 {algorithm} 对数据进行排序，数据长度: {len(data)}")
        
        try:
            # 复制数据以避免修改原始数据
            data_copy = data.copy()
            
            # 执行排序
            sorted_data = self.algorithms[algorithm](data_copy, **kwargs)
            
            return {
                "algorithm": algorithm,
                "original_data": data,
                "sorted_data": sorted_data,
                "data_length": len(data),
                "status": "success"
            }
            
        except Exception as e:
            logger.error(f"排序失败: {e}")
            return {
                "algorithm": algorithm,
                "original_data": data,
                "sorted_data": None,
                "error": str(e),
                "status": "error"
            }
    
    def compare_algorithms(self, data: List[Any], algorithms: List[str] = None) -> Dict[str, Any]:
        """比较多个排序算法的性能"""
        import time
        
        if algorithms is None:
            algorithms = self.get_available_algorithms()
        
        results = {}
        
        for algorithm in algorithms:
            if algorithm not in self.algorithms:
                logger.warning(f"跳过不支持的算法: {algorithm}")
                continue
            
            try:
                # 复制数据
                data_copy = data.copy()
                
                # 计时
                start_time = time.time()
                sorted_data = self.algorithms[algorithm](data_copy)
                end_time = time.time()
                
                execution_time = end_time - start_time
                
                results[algorithm] = {
                    "execution_time": execution_time,
                    "sorted_data": sorted_data,
                    "status": "success"
                }
                
                logger.info(f"算法 {algorithm} 执行时间: {execution_time:.6f}秒")
                
            except Exception as e:
                results[algorithm] = {
                    "execution_time": None,
                    "error": str(e),
                    "status": "error"
                }
                logger.error(f"算法 {algorithm} 执行失败: {e}")
        
        return {
            "original_data": data,
            "results": results,
            "algorithms_tested": list(results.keys())
        }
    
    def validate_sorted_data(self, data: List[Any]) -> bool:
        """验证数据是否已排序"""
        if not data:
            return True
        
        for i in range(len(data) - 1):
            if data[i] > data[i + 1]:
                return False
        
        return True


# 全局排序API实例
sort_api = SortAPI()